package cn.iocoder.yudao.module.book.service.WeChat;

import cn.iocoder.yudao.module.book.controller.app.login.vo.WeChatLoginRespVO;
import cn.iocoder.yudao.module.book.controller.app.login.vo.WeChatSession;
import cn.iocoder.yudao.module.book.dal.dataobject.users.userDTODO;
import cn.iocoder.yudao.module.book.service.users.userDTOService;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenCreateReqDTO;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenRespDTO;
import cn.iocoder.yudao.module.system.enums.oauth2.OAuth2ClientConstants;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import cn.iocoder.yudao.module.system.api.oauth2.OAuth2TokenApi;

import javax.annotation.Resource;

@Service
public class WeChatUserService {

    @Resource
    private userDTOService userService;

    @Value("${wx.mp.app-id}")
    private String appid;

    @Value("${wx.mp.secret}")
    private String appsecret;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private OAuth2TokenApi oauth2TokenApi;

//    @Value("${wx.mp.token-url}")

//    @Resource
//    private SocialClientService socialClientService;

    public WeChatLoginRespVO loginByWeChatApplet(String code) {
        // 1. 调用微信接口，换取 openid 和 session_key
        WeChatSession session = getWeChatSession(code);

        // 2. 根据 openid 获取或创建用户
        userDTODO user = userService.getByOpenId(session.getOpenid());
        if (user == null) {
            user = userService.registerWeChatUser(session.getOpenid(), session.getSessionKey());
        }

        // 3. 生成 Token（如 JWT）
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(new OAuth2AccessTokenCreateReqDTO()
                .setUserId(user.getUserId()).setUserType(1)
                .setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT));

        // 4. 构建返回结果
        WeChatLoginRespVO resp = new WeChatLoginRespVO();
        resp.setToken(accessTokenRespDTO.getAccessToken());
        resp.setUserId(user.getUserId());
        resp.setOpenid(user.getOpenid());
        resp.setNickname(user.getNickname());
        resp.setAvatarUrl(user.getAvatarUrl());

        return resp;
    }

    private WeChatSession getWeChatSession(String code) {
        String appId = appid;
        String appSecret = appsecret;
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        String response = restTemplate.getForObject(url, String.class);
        return JSON.parseObject(response, WeChatSession.class);
    }

//    private String generateToken(Long userId) {
//        // 使用 JWT 或 Redis 生成 Token
//        return JwtUtils.generateToken(userId.toString());
//    }
}
